<template>
  <div class="toTop">
      <div class="gotop" v-show="gotop" @click="toTop">
           <p>T</p>
          <p>O</p>
          <p>P</p></div>
  </div>
</template>

<script>
export default {
  name: 'toTop',
  data() {
    return {
      gotop: false,
    }
  },
  mounted() {
    // 此处true需要加上，不加滚动事件可能绑定不成功
    window.addEventListener('scroll', this.handleScroll, true)
  },
  methods: {
    handleScroll() {
      const scrolltop = document.documentElement.scrollTop || document.body.scrollTop
      scrolltop > 30 ? (this.gotop = true) : (this.gotop = false)
    },
    toTop() {
      let top = document.documentElement.scrollTop || document.body.scrollTop
      // 实现滚动效果
      const timeTop = setInterval(() => {
        document.body.scrollTop = document.documentElement.scrollTop = top -= 50
        if (top <= 0) {
          clearInterval(timeTop)
        }
      }, 10)
    },
  },
}
</script>

<style lang="less" scoped>
.gotop{
    width: 90px;
    height: 150px;
    background-color: white;
    position: fixed;
    top: 800px;
    left: 650px;
    border-radius: 40px;
    opacity: .6;
    border:2px solid black;
    p{
        height: 3px;
        text-align: center;
        color: black;
        font-weight: 900;
    }
}
</style>
